package com.raul.AgendaAndroid;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.raul.AgendaAndroid.Conexion.Connection;
import com.raul.AgendaAndroid.beans.Agenda;
import com.raul.AgendaAndroid.util.URLKeys;
import com.raul.AgendaAndroid.util.Utilidades;

public class MainActivity extends Activity {

	ListView lvContactos;
	ArrayList<Agenda> contactosList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		new MakePetitionTask(this).execute();

		Button btNuevoContacto = (Button) findViewById(R.id.nuevoContacto);
		btNuevoContacto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent newContact = new Intent(MainActivity.this,
						NewContactActivity.class);
				startActivity(newContact);
			}
		});
	}

	private class ContactosListViewAdapter extends ArrayAdapter<Agenda> {
		private final ArrayList<Agenda> items;

		public ContactosListViewAdapter(Context context,
				int textViewResourceId, ArrayList<Agenda> objects) {
			super(context, textViewResourceId, objects);

			this.items = objects;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;

			if (v == null) {
				LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = layoutInflater.inflate(R.layout.row_contacto, null);
			}
			Agenda agenda = items.get(position);
			if (agenda != null) {
				((TextView) v.findViewById(R.id.lb_nombreContacto))
						.setText(agenda.getNombre() + " "
								+ agenda.getApellido());
			}
			return v;
		}
	}

	class MakePetitionTask extends AsyncTask<Void, Void, String> {
		private ProgressDialog progressDialog;
		private final Context context;

		public MakePetitionTask(Context context) {
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(context, "",
					"Espere por favor");
		}

		@Override
		protected String doInBackground(Void... urls) {
			try {
				Connection connection = new Connection();
				ArrayList<String> parametros = new ArrayList<String>();
				JSONArray jsonArray = connection.getServerData(parametros,
						URLKeys.ALL);
				if (jsonArray != null) {
					contactosList = new ArrayList<Agenda>();
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						if (jsonObject != null) {
							Agenda agenda = new Agenda();
							agenda.setId(jsonObject.getInt("id"));
							agenda.setNombre(jsonObject.getString("nombre"));
							agenda.setApellido(jsonObject.getString("apellido"));
							contactosList.add(agenda);
						}
					}
				}

			} catch (Exception e) {
				Utilidades.alertas(e.getMessage(), this.context);
			}
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			this.progressDialog.cancel();
			if (contactosList != null && contactosList.size() > 0) {
				lvContactos = (ListView) findViewById(R.id.lv_contactos);
				lvContactos.setAdapter(new ContactosListViewAdapter(
						MainActivity.this, R.id.lv_contactos, contactosList));
				lvContactos
						.setOnItemClickListener(new AdapterView.OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> listAgenda,
									View arg1, int position, long arg3) {
								Agenda agenda = (Agenda) listAgenda
										.getItemAtPosition(position);
								Bundle bundle = new Bundle();
								String id = String.valueOf(agenda.getId());
								bundle.putString("id", id);

								Intent activityDetails = new Intent(
										MainActivity.this,
										DetailsActivity.class);
								activityDetails.putExtras(bundle);
								startActivityForResult(activityDetails, 0);

							}
						});

			}
		}

		/*
		 * private void mensaje(String msg) { // se prepara la alerta creando
		 * nueva instancia AlertDialog.Builder dialogBuilder = new
		 * AlertDialog.Builder( this.context); // seleccionamos la cadena a
		 * mostrar dialogBuilder.setMessage(msg); // elegimo un titulo y
		 * configuramos para que se pueda quitar
		 * dialogBuilder.setCancelable(true).setTitle("Titulo de la alerta"); //
		 * mostramos el dialogBuilder dialogBuilder.create().show(); }
		 */
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
